/*
 * Copyright 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.apps.nowinandroid.demo.view

import android.util.Log
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.Movie
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.google.samples.apps.nowinandroid.demo.viewmodel.MovieInfoViewModel
import coil.compose.AsyncImage
import com.google.samples.apps.nowinandroid.demo.model.MovieInfo

/**
 * 电影列表界面
 * @param imdbID 电影的imdbID
 * @param viewModel 视图模型，用于管理数据和状态
 * @param modifier 修饰符，用于自定义布局
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MovieInfoView(
    title: String?,
    viewModel: MovieInfoViewModel,
    modifier: Modifier = Modifier,
    onBackClick: () -> Unit
) {
    // 记录界面被调用的日志
    Log.d("tongkeqiang", "MovieInfoView composable called with imdbID: $title")

    // 使用 imdbID 从 ViewModel 中获取电影详情
    LaunchedEffect(title) {
        if (title != null) {
            viewModel.loadMovieInfo(title)
        }
    }




// 从 ViewModel 中收集状态
    val movie by viewModel.movieInfo.collectAsState() // 电影详情数据
    val isLoading by viewModel.isLoading.collectAsState() // 加载状态
    val error by viewModel.error.collectAsState() // 错误信息

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(title ?: "电影详情") },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                ),
                windowInsets = WindowInsets(0.dp)
            )
        }
    ) { paddingValues ->
        Box(
            modifier = modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            when {
                // 显示加载中状态
                isLoading -> {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            color = MaterialTheme.colorScheme.primary
                        )
                    }
                }
                // 显示错误信息
                error != null -> {
                    Column(
                        modifier = Modifier
                            .align(Alignment.Center)
                            .padding(16.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            imageVector = Icons.Default.Error,
                            contentDescription = null,
                            modifier = Modifier.size(48.dp),
                            tint = MaterialTheme.colorScheme.error
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = error ?: "加载失败",
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.error
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Button(
                            onClick = { viewModel.retry() },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = MaterialTheme.colorScheme.primary
                            )
                        ) {
                            Text("重试")
                        }
                    }
                }
                // 显示空数据状态
                movie == null -> {
                    Column(
                        modifier = Modifier
                            .align(Alignment.Center)
                            .padding(16.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Icon(
                            imageVector = Icons.Default.Movie,
                            contentDescription = null,
                            modifier = Modifier.size(48.dp),
                            tint = MaterialTheme.colorScheme.primary
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = "暂无数据",
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
                // 显示电影详情
                else -> {
                    movie?.let { nonNullMovie ->
                        MovieInfoItem(movie = nonNullMovie)
                    }
                }
            }
        }
    }
}

/**
 * 单个电影项的显示组件
 * @param movie 电影数据
 */
@Composable
private fun MovieInfoItem(movie: MovieInfo) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .verticalScroll(rememberScrollState())
            .padding(16.dp)
    ) {
        // 电影海报
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .height(300.dp)
                .padding(bottom = 16.dp),
            elevation = CardDefaults.cardElevation(4.dp)
        ) {
            AsyncImage(
                model = movie.Poster,
                contentDescription = "Movie Poster",
                modifier = Modifier.fillMaxSize()
            )
        }

        // 基本信息卡片
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            ),
            elevation = CardDefaults.cardElevation(2.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = movie.Title,
                    style = MaterialTheme.typography.headlineMedium,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                
                Row(
                    modifier = Modifier.padding(bottom = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    Text(
                        text = "年份: ${movie.Year}",
                        style = MaterialTheme.typography.bodyLarge
                    )
                    Text(
                        text = "•",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
                    )
                    Text(
                        text = "评分: ${movie.imdbRating}",
                        style = MaterialTheme.typography.bodyLarge
                    )
                }

                // 评分信息
                Row(
                    horizontalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    Text(
                        text = "IMDB评分: ${movie.imdbRating}",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    Text(
                        text = "•",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
                    )
                    Text(
                        text = "评分人数: ${movie.imdbVotes}",
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            }
        }

        // 详细信息卡片
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            ),
            elevation = CardDefaults.cardElevation(2.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                DetailSection(title = "导演", content = movie.Director)
                DetailSection(title = "演员", content = movie.Actors)
                DetailSection(title = "类型", content = movie.Genre)
                DetailSection(title = "剧情简介", content = movie.Plot)
                DetailSection(title = "语言", content = movie.Language)
                DetailSection(title = "国家", content = movie.Country)
                DetailSection(title = "获奖情况", content = movie.Awards)
            }
        }
    }
}

@Composable
private fun DetailSection(title: String, content: String) {
    Column(
        modifier = Modifier.padding(vertical = 8.dp)
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.primary
        )
        Text(
            text = content,
            style = MaterialTheme.typography.bodyMedium,
            modifier = Modifier.padding(top = 4.dp)
        )
    }
} 